package com.aiyige.page.my.settings;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventGprsNotificationConfigChange;
import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.share.ShareAppDialog;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.crash.CrashUtils;
import com.aiyige.utils.widget.ShSwitchView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.netease.nimlib.sdk.NIMClient;
import com.tencent.bugly.beta.Beta;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by xiachao on 2017/12/18.
 */

@Route(path = ARouterConfig.SettingsPage)
public class SettingsPage extends BaseActivity {

    @BindView(R.id.switch_enable_notification)
    ShSwitchView switchEnableNotification;
    @BindView(R.id.switch_wifi_data_remind)
    ShSwitchView switchEnableWifiDataRemind;
    @BindView(R.id.right_arrows_1)
    ImageView rightArrows1;
    @BindView(R.id.cache_count_value_tv)
    TextView cacheCountValueTv;
    @BindView(R.id.settings_clean_cache_layout)
    RelativeLayout settingsCleanCacheLayout;
    @BindView(R.id.right_arrows_2)
    ImageView rightArrows2;
    @BindView(R.id.settings_current_version_name_tv)
    TextView settingsCurrentVersionNameTv;// 当前版本名称1.0
    @BindView(R.id.settings_check_update_layout)
    RelativeLayout settingsCheckUpdateLayout;//检查版本
    @BindView(R.id.settings_new_version_tag)
    View settingsCheckUpdateRedTag;//检查版本那个右上角的红色标志
    @BindView(R.id.settings_about_us_layout)
    RelativeLayout settingsAboutUsLayout;// 产品简介
    @BindView(R.id.settings_share_app_layout)
    RelativeLayout settingsShareAppLayout;// 推荐给好友
    @BindView(R.id.settings_give_us_score_layout)
    RelativeLayout settingsGiveUsScoreLayout;// 给我们评分
    @BindView(R.id.settings_logout_layout)
    RelativeLayout settingsLogoutLayout;// 退出登录
    @BindView(R.id.settings_check_update_tag)
    TextView settingsCheckUpdateTag;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_setting);
        ButterKnife.bind(this);
        initTitleLayout(getString(R.string.setting_and_feedback));
        settingsCurrentVersionNameTv.setText("v" + VersionUtil.getCurrentVersion(this));
        cacheCountValueTv.setText(CacheUtils.getCacheSize(this));
        switchEnableNotification.setOn(ConfigUltis.isEnableMessagePush());// 推送接受的开关
        switchEnableNotification.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                ConfigUltis.setMessagePushEnable(isOn);
                if (isOn) {
                    JPushInterface.resumePush(MyApp.getAppContext());
                } else {
                    JPushInterface.stopPush(MyApp.getAppContext());
                }
                NIMClient.toggleNotification(isOn);
            }
        });
        switchEnableWifiDataRemind.setOn(ConfigUltis.isEnableGprsNotification());// 移动网络提醒
        switchEnableWifiDataRemind.setOnSwitchStateChangeListener(new ShSwitchView.OnSwitchStateChangeListener() {
            @Override
            public void onSwitchStateChange(boolean isOn) {
                ConfigUltis.setGprsNotificationEnable(isOn);
                if (isOn) {
                    PublishUtil.pauseAll();
                    DownloadUtil.pauseAll();
                }
                EventBus.getDefault().post(new EventGprsNotificationConfigChange(isOn));
            }
        });
        settingsLogoutLayout.setVisibility(LoginManager.isLogin() ? View.VISIBLE : View.INVISIBLE);
//        if (Build.VERSION.SDK_INT >= 26) {
//            settingsShareAppLayout.setVisibility(View.GONE);
//        } else {
//            settingsShareAppLayout.setVisibility(View.VISIBLE);
//        }
        settingsShareAppLayout.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.settings_clean_cache_layout, R.id.settings_check_update_layout, R.id.settings_about_us_layout,
            R.id.settings_share_app_layout, R.id.settings_give_us_score_layout, R.id.settings_logout_tv,
            R.id.settings_service,R.id.settings_account_safety_layout,R.id.view_server_switch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.settings_clean_cache_layout:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CacheUtils.clearCache(SettingsPage.this);
                    }
                }).start();
                ToastX.show(getString(R.string.cleaned));
                cacheCountValueTv.setText("0M");
                break;
            case R.id.settings_check_update_layout:
                Beta.checkUpgrade();
                break;
            case R.id.settings_about_us_layout:
                ARouter.getInstance().build(ARouterConfig.WebViewPage)
                        .withString("url", "https://download.dance365.com/").withBoolean("noTitleBar", false).navigation();
                break;
            case R.id.settings_share_app_layout:
                ShareAppDialog.newInstance(this).shareApp();
                break;
            case R.id.settings_give_us_score_layout:
                Uri uri = Uri.parse("market://details?id=" + getPackageName());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(Intent.createChooser(intent, "请选择要查看的市场软件"));
                break;
            case R.id.settings_logout_tv:
                LoginManager.getInstance().logout();
                ToastX.show(getString(R.string.logout_success));
                settingsLogoutLayout.setVisibility(View.INVISIBLE);
                finish();
                break;
            case R.id.settings_service:
                Intent intent1=  new Intent(Intent.ACTION_DIAL);
                intent1.setData(Uri.parse("tel:4008081758"));
                startActivity(intent1);
                break;
            case R.id.settings_account_safety_layout:
                ARouter.getInstance().build(ARouterConfig.AccountPage).navigation();
                break;
            case R.id.view_server_switch:
                testLog();
                break;
        }
    }


    private long exitTime = 0;
    private int clickTimes = 0;
    private void testLog() {
        if (clickTimes == 0) {
            exitTime = System.currentTimeMillis();
        }
        clickTimes++;
        if (System.currentTimeMillis() - exitTime > 5000) {
            clickTimes = 0;
            exitTime = 0;
        } else if (clickTimes == 3) {
//            throw new RuntimeException("Test exception by wudao");
            CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_json_parsing, "测试异常：\n" + System.currentTimeMillis(), AiyigeExceptionModel.rating_3);
        }
    }

    private void showLogoutDialog() {
//        final ConfirmDialog dialog = new ConfirmDialog(this);
//        dialog.setTitle(R.string.text_prompt);
//        dialog.setMessage(getString(R.string.prompt_logout));
//        dialog.setCancelListener(getString(R.string.cancel),
//                new View.OnClickListener() {
//                    @Override
//                    public void onClick(View arg0) {
//                        dialog.dismiss();
//                    }
//                });
//        dialog.setOkListener(getString(R.string.ok),
//                new View.OnClickListener() {
//                    @Override
//                    public void onClick(View arg0) {
//                        dialog.dismiss();
//                        showLoading(getString(R.string.logouting));
//                        LoginManager.getInstance().requestLogout(getActivity(), new Handler() {
//                            @Override
//                            public void handleMessage(Message msg) {
//                                hideLoading();
//                                switch (msg.what) {
//                                    case 0://退出登录失败
//
//                                        break;
//                                    case 1://退出登录成功
//                                        refreshLoginStatus();
//                                        SyncManager.getInstance().cancelAllDownload();
//                                        ToastX.show(SettingsActivity.this.getString(R.string.toast_success_logout));
//                                        MyMessageUtil.fetchNewMessageCount();
//                                        TagAliasOperatorHelper.getInstance().cleanLoginTagAndAlias(MyApplication.getAppContext());
//                                        finish();
//                                        break;
//
//                                }
//
//                            }
//                        });
//
//                    }
//                });
//        dialog.show();
    }
}
